package org.fu.crowd.mvc.config;

import org.fu.crowd.constant.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@EnableGlobalMethodSecurity(prePostEnabled = true)//启用全局方法权限控制
//对应方法上加 @PreAuthorize("hasRole('部长')")
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource//就是CrowdUserDetailsService，因为继承了
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        //有加密
        builder.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
    }

    /**
     * 拦截设置
     * @param security
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
                .authorizeRequests()
                .antMatchers("/","/admin-login")
                .permitAll()
                .antMatchers("/bootstrap/**","/crowd/**","/css/**",
                        "/fonts/**","/img/**","/jquery/**","/script/**",
                        "/ztree/**")
                .permitAll()//无条件访问
                .antMatchers("/main/mainuser")
                .hasRole("经理")
//                .access("hasRole('经理') AND hasAuthority('user:get')")//既要是经理，也要有权限user:get
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        httpServletRequest.setAttribute("exception",new Exception(CrowdConstant.MESSAGE_ACCESS_DENIED));
                        httpServletRequest.getRequestDispatcher("/system-error").forward(httpServletRequest,httpServletResponse);
                    }
                })
                .and()
                .csrf()//防跨站请求伪造功能
                .disable()//禁用
                .formLogin()//开启表单登录功能
                .loginPage("/admin-login")//登录页
                .loginProcessingUrl("/admin/login")//处理登录请求的地址
                .defaultSuccessUrl("/redirect")//成功后去的页面
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        httpServletRequest.setAttribute("exception",new Exception(CrowdConstant.MESSAGE_LOGIN_FAILED));
                        httpServletRequest.getRequestDispatcher("/admin-login").forward(httpServletRequest,httpServletResponse);
                    }
                })
                .usernameParameter("loginAcct")//登录账号的参数名
                .passwordParameter("userPswd")//登录密码的参数名
                .and()
                .logout()//退出登录
                .logoutUrl("/admin/logout")//退出登录的地址
                .logoutSuccessUrl("/")//退出成功后去的地址
                .invalidateHttpSession(true)
                ;
    }





    /**
     *      密码加密类
     * @return
     */
    @Bean
    public BCryptPasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
